//
//  FMViewController.m
//  leisure
//
//  Created by xalo on 16/4/18.
//  Copyright © 2016年 Mr.wangYongxu. All rights reserved.
//

#import "FMViewController.h"
#import "FMModel.h"
#import "ReadScrollPictureModel.h"
#import "FMTableViewCell.h"
#import "FMListViewController.h"

#define kFMRefreshURl @"http://api2.pianke.me/ting/radio_list"
#define kFMURL @"http://api2.pianke.me/ting/radio"
#define HOTLISTKEY @"hotlist"
#define AllLISTKEY @"alllist"
#define SCROLLKEY @"carousel"

@interface FMViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic, strong)NSMutableArray* alllistModelArr;
@property(nonatomic, strong)NSMutableArray* hotlistModelArr;
@property(nonatomic, strong)SDCycleScrollView* scrollPicture;//轮播图
@property(nonatomic, strong)NSMutableArray* scrollPictureModelArr;//图片模型
@property(nonatomic, strong)UITableView* tableView;//系统图
@property(nonatomic, assign)NSInteger startValue;
@property(nonatomic, retain)NSMutableDictionary* parameterDic;//参数
@property(nonatomic, assign)NSInteger total;

@end

@implementation FMViewController
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}




- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    [self.view setBackgroundColor:[UIColor brownColor]];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self fetchDatawithURL:kFMURL parameters:nil];
    [self setMJFreshUpDown];
    [self.tableView setTableHeaderView:self.scrollPicture];
    [self.view addSubview:self.tableView];
    [self.tableView registerNib:[UINib nibWithNibName:@"FMTableViewCell" bundle:nil] forCellReuseIdentifier:@"FMTableViewCell"];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Menu"
                                                                             style:UIBarButtonItemStylePlain
                                                                            target:self
                                                                            action:@selector(presentLeftMenuViewController:)];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(UITableView *)tableView{
    
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, kViewWidth, kViewHeight) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}
-(SDCycleScrollView *)scrollPicture{
    
    if (!_scrollPicture) {
        _scrollPicture = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, kViewWidth, kViewHeight/4) delegate:nil placeholderImage:[UIImage imageNamed:@"placeHolderPicture"]];
    }
    return _scrollPicture;
}

-(NSMutableArray *)scrollPictureModelArr{
    
    if (!_scrollPictureModelArr) {
        _scrollPictureModelArr = [NSMutableArray array];
    }
    return _scrollPictureModelArr;
}
-(NSMutableArray *)hotlistModelArr{
    
    if (!_hotlistModelArr) {
        _hotlistModelArr = [NSMutableArray array];
    }
    return _hotlistModelArr;
}

-(NSMutableArray *)alllistModelArr{
    
    if (!_alllistModelArr) {
        _alllistModelArr = [NSMutableArray array];
    }
    return _alllistModelArr;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (section==0) {
        return @"热门电台";
    }else{
        return @"全部电台";
    }
}


#pragma mark - <UItableViewDatasource,UITableViewDelegate>
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    FMTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"FMTableViewCell" forIndexPath:indexPath];
    if (indexPath.section==0) {
        [cell setCellWithFMModel:self.hotlistModelArr[indexPath.row]];
    }else{
        [cell setCellWithFMModel:self.alllistModelArr[indexPath.row]];
    }
    return cell;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section==0) {
         return self.hotlistModelArr.count;
    }else{
         return self.alllistModelArr.count;
    }
   
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return kViewWidth/3;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    FMlistViewController* FMDetail = [[UIStoryboard storyboardWithName:@"Radio" bundle:nil] instantiateViewControllerWithIdentifier:@"FMlistViewController"];
    if (indexPath.section == 0) {
        FMDetail.model = self.hotlistModelArr[indexPath.row];
    }else{
        FMDetail.model = self.alllistModelArr[indexPath.row];
    }
    [self.navigationController pushViewController:FMDetail animated:YES];
}

#pragma mark - AFNetWorking
-(void)fetchDatawithURL:(NSString*)url parameters:(NSDictionary*)parameter{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    AFHTTPSessionManager* manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url parameters:parameter progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"电台数据请求成功");
        NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSDictionary* dataDic = [dic objectForKey:@"data"];
        NSArray* hotArray = [dataDic objectForKey:HOTLISTKEY];
        for (int i = 0; i < hotArray.count; i++) {
            FMModel* model = [[FMModel alloc] init];
            [model setValuesForKeysWithDictionary:hotArray[i]];
            [self.hotlistModelArr addObject:model];
        }
        NSArray* alllistArr = [dataDic objectForKey:AllLISTKEY];
        for (int i = 0; i< alllistArr.count; i++) {
            FMModel* model = [[FMModel alloc] init];
            [model setValuesForKeysWithDictionary:alllistArr[i]];
            [self.alllistModelArr addObject:model];
        }
        NSArray* scrollPictureDataArr = [dataDic objectForKey:SCROLLKEY];
        NSMutableArray* urlArr = [NSMutableArray array];
        for (int i = 0; i < scrollPictureDataArr.count; i++) {
            ReadScrollPictureModel* model = [[ReadScrollPictureModel alloc]init];
            [model setValuesForKeysWithDictionary:scrollPictureDataArr[i]];
            [self.scrollPictureModelArr addObject:model];
            [urlArr addObject:model.img];
        }       
        self.scrollPicture.imageURLStringsGroup = urlArr;

        [self.tableView reloadData];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"电台数据请求失败%@",error);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}


-(void)refreshDataWithUrl:(NSString*)url parameter:(NSDictionary*)dic{

//    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    AFHTTPSessionManager* manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        _total = [[dic objectForKey:@"data"][@"total"] integerValue];
        NSArray* array = [dic objectForKey:@"data"][@"list"];
        for (int i = 0; i< array.count; i++) {
            FMModel* model = [[FMModel alloc] init];
            [model setValuesForKeysWithDictionary:array[i]];
            [self.alllistModelArr addObject:model];
        }
        [self.tableView reloadData];
        [self.tableView.mj_footer endRefreshing];
        [self.tableView.mj_header endRefreshing];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

    }];
}

- (void)setMJFreshUpDown{
    _startValue = 0;
    NSDictionary* dic = @{@"start":@(_startValue),@"limit":@10};
    _parameterDic = [NSMutableDictionary dictionaryWithDictionary:dic];
    __weak FMViewController *weakSelf = self;
    //下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf.alllistModelArr removeAllObjects];
        [weakSelf.hotlistModelArr removeAllObjects];
        [weakSelf.scrollPictureModelArr removeAllObjects];
        [weakSelf fetchDatawithURL:kFMURL parameters:nil];
    }];
    //上拉加载
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        _startValue += 10;
        [_parameterDic setValue:@(_startValue) forKey:@"start"];
        if ( !_total||_startValue < _total) {
            [weakSelf refreshDataWithUrl:kFMRefreshURl parameter:_parameterDic];
        }else{
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }

    }];


}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
